<template>
  <div class="email-container">
    <div class="header">
      <h1>邮件发送</h1>
    </div>

    <el-tabs v-model="activeTab" class="email-tabs">
      <el-tab-pane label="简单邮件" name="simple">
        <el-form :model="simpleForm" :rules="emailRules" ref="simpleFormRef" label-width="100px">
          <el-form-item label="收件人" prop="to">
            <el-input v-model="simpleForm.to" placeholder="请输入收件人邮箱" />
          </el-form-item>
          <el-form-item label="主题" prop="subject">
            <el-input v-model="simpleForm.subject" placeholder="请输入邮件主题" />
          </el-form-item>
          <el-form-item label="收件人姓名" prop="recipientName">
            <el-input v-model="simpleForm.recipientName" placeholder="请输入收件人姓名（可选）" />
          </el-form-item>
          <el-form-item label="邮件内容" prop="message">
            <el-input
              v-model="simpleForm.message"
              type="textarea"
              rows="5"
              placeholder="请输入邮件内容"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSendSimpleEmail" :loading="loading"
              >发送邮件</el-button
            >
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="产品邮件" name="product">
        <el-form
          :model="productForm"
          :rules="productEmailRules"
          ref="productFormRef"
          label-width="100px"
        >
          <el-form-item label="收件人" prop="to">
            <el-input v-model="productForm.to" placeholder="请输入收件人邮箱" />
          </el-form-item>
          <el-form-item label="收件人姓名" prop="recipientName">
            <el-input v-model="productForm.recipientName" placeholder="请输入收件人姓名（可选）" />
          </el-form-item>
          <el-form-item label="选择产品" prop="productId">
            <el-select v-model="productForm.productId" placeholder="请选择产品" style="width: 100%">
              <el-option
                v-for="product in products"
                :key="product.id"
                :label="product.name"
                :value="product.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSendProductEmail" :loading="loading"
              >发送产品邮件</el-button
            >
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getProducts, type Product } from '@/api/product'
import {
  sendSimpleEmail as apiSendSimpleEmail,
  sendProductEmail as apiSendProductEmail,
  type EmailRequest,
  type ProductEmailRequest,
} from '@/api/email'

const activeTab = ref('simple')
const loading = ref(false)
const simpleFormRef = ref()
const productFormRef = ref()
const products = ref<Product[]>([])

const simpleForm = reactive<EmailRequest>({
  to: '',
  subject: '',
  recipientName: '',
  message: '',
})

const productForm = reactive<ProductEmailRequest>({
  to: '',
  productId: 0,
  recipientName: '',
})

const emailRules = {
  to: [
    { required: true, message: '请输入收件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  subject: [{ required: true, message: '请输入邮件主题', trigger: 'blur' }],
  message: [{ required: true, message: '请输入邮件内容', trigger: 'blur' }],
}

const productEmailRules = {
  to: [
    { required: true, message: '请输入收件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
}

onMounted(async () => {
  await fetchProducts()
})

const fetchProducts = async () => {
  try {
    const res = await getProducts()
    if (res.success && res.data) {
      products.value = res.data
    }
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
  }
}

const handleSendSimpleEmail = async () => {
  if (!simpleFormRef.value) return

  await simpleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const res = await apiSendSimpleEmail(simpleForm)
        if (res.success) {
          ElMessage.success('邮件发送成功')
          simpleFormRef.value.resetFields()
        } else {
          ElMessage.error(res.message || '邮件发送失败')
        }
      } catch (error) {
        console.error('邮件发送失败:', error)
        ElMessage.error('邮件发送失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

const handleSendProductEmail = async () => {
  if (!productFormRef.value) return

  await productFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const res = await apiSendProductEmail(productForm)
        if (res.success) {
          ElMessage.success('产品邮件发送成功')
          productFormRef.value.resetFields()
        } else {
          ElMessage.error(res.message || '产品邮件发送失败')
        }
      } catch (error) {
        console.error('产品邮件发送失败:', error)
        ElMessage.error('产品邮件发送失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.email-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.email-tabs {
  margin-top: 20px;
}
</style>
